package com.windhc.service;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import com.windhc.mapper.CronMapper;
import com.windhc.model.Cron;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author windhc
 */
@Service
public class CronService {
    private static final Logger logger = LoggerFactory.getLogger(CronService.class);

    @Resource
    private CronMapper cronMapper;

    public void add(Cron cron) {
        // 添加定时任务
        String schedulerId = CronUtil.schedule(cron.getCronStr(), new Task() {
            @Override
            public void execute() {
                // 执行具体的逻辑,例如根据cron中的execContent字段来判断
                logger.info(".....");
            }
        });
        cron.setSchedulerId(schedulerId);
        cron.setStatus(1);
        cron.setCreatedAt(System.currentTimeMillis());
        cronMapper.insert(cron);
    }

    public void delete(String schedulerId) {
        CronUtil.remove(schedulerId);
        cronMapper.deleteBy(schedulerId);
    }

    public List<Cron> findAll() {
        return cronMapper.selectList(null);
    }
}
